package com.yhhvip.lottery.service.impl;

import com.yhhvip.lottery.dao.mybatis.mapper.LotSysRoleResourcesMapper;
import com.yhhvip.lottery.dao.mybatis.mapper.LotSysUserRoleMapper;
import com.yhhvip.lottery.dao.mybatis.model.LotSysResourcesExample;
import com.yhhvip.lottery.dao.mybatis.model.LotSysRoleResources;
import com.yhhvip.lottery.dao.mybatis.model.LotSysRoleResourcesExample;
import com.yhhvip.lottery.domain.ReqLotSysRoleResources;
import com.yhhvip.lottery.service.RoleResourcesService;
import com.yhhvip.lottery.shiro.ShiroService;
import com.yhhvip.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by yangqj on 2017/4/26.
 */
@Service("roleResourcesService")
public class RoleResourcesServiceImpl implements RoleResourcesService {

    @Autowired
    private LotSysRoleResourcesMapper roleResourcesMapper;

    @Resource
    private ShiroService shiroService;

    @Autowired
    private LotSysUserRoleMapper userRoleMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @CacheEvict(cacheNames = "resources", allEntries = true)
    public void addRoleResources(ReqLotSysRoleResources roleResources) {
        //删除
        LotSysRoleResourcesExample roleResourcesExample = new LotSysRoleResourcesExample();
        roleResourcesExample.createCriteria().andRoleIdEqualTo(roleResources.getRoleId());
        roleResourcesMapper.deleteByExample(roleResourcesExample);
        //添加
            String[] resourcesArr = roleResources.getResourcesId().split(",");
            for (String resourcesId : resourcesArr) {
                LotSysRoleResources resources = new LotSysRoleResources();
                resources.setRoleId(roleResources.getRoleId());
                resources.setResourcesId(resourcesId);
                roleResourcesMapper.insertSelective(resources);
            }
        List<Long> userIds= userRoleMapper.findUserIdByRoleId(roleResources.getRoleId());
        //更新当前登录的用户的权限缓存
        shiroService.clearUserAuthByUserId(userIds);


    }
}
